public with sharing class DataFormatter {
	
	public string phoneFormatter(String phone){
		
		/*Extracts all numbers from string*/
		Pattern numbersOnly = Pattern.compile('[^\\d]');
		phone = numbersOnly.matcher(phone).replaceAll('');
		system.debug(phone);
		
		/*Do formatting only if its a 10 digit number. Format - (XXX) XXX-XXXX*/
		if(phone.length()==10 && Pattern.matches('^[2-9][0-9]+$',phone)){
			String formattedPhone = '('+phone.substring(0,3)+') '+phone.substring(3,6)+'-'+phone.substring(6,10);
			System.debug(formattedPhone);
			return formattedPhone;
		}
		return 'Failed';
	}
}